package com.cloudwise.monitoring_system.config;


import com.cloudwise.monitoring_system.util.RedisProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisClusterConfiguration;
import org.springframework.data.redis.connection.RedisNode;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import redis.clients.jedis.JedisPoolConfig;

import javax.annotation.Resource;

@Configuration
public class RedisConfig {

    @Resource
    private RedisProperties redisProperties;


    /**
     * 配置redis链接工厂类
     * @return jedisConnectionFactory
     */
    @Bean
    public JedisConnectionFactory jedisConnectionFactory(){
        JedisConnectionFactory jedisConnectionFactory =
                new JedisConnectionFactory(clusterConfig(),poolConfig());
        return jedisConnectionFactory;
    }

    /**
     * 实例化redis集群配置
     * @return redisClusterConfiguration
     */
    @Bean
    public RedisClusterConfiguration clusterConfig(){
        RedisClusterConfiguration redisClusterConfiguration =new RedisClusterConfiguration();
        String nodes = redisProperties.getNodes();
        if(nodes!=null){
            String[] redisNodeArray = nodes.split(",");
            for (String redisNode : redisNodeArray) {
                String[] hostAndPortArray = redisNode.split(":");
                RedisNode node = new RedisNode(hostAndPortArray[0],Integer.valueOf(hostAndPortArray[1]));
                redisClusterConfiguration.addClusterNode(node);
            }
        }
        return redisClusterConfiguration;
    }

    /**
     * 实例化redis集群的连接池
     * @return jedisPoolConfig
     */
    @Bean
    public JedisPoolConfig poolConfig(){
        JedisPoolConfig jedisPoolConfig =new JedisPoolConfig();
        jedisPoolConfig.setMaxIdle(redisProperties.getMaxWaitMillis());
        jedisPoolConfig.setMaxTotal(redisProperties.getMaxTotal());
        jedisPoolConfig.setMaxWaitMillis(redisProperties.getMaxWaitMillis());
        jedisPoolConfig.setTestOnBorrow(redisProperties.isTestOnBorrow());
        return jedisPoolConfig;
    }

}
